﻿using System.Collections.Generic;
using MugenInjection.Infrastructure;
using MugenInjection.Interface;

namespace MugenInjection.Scope
{
    /// <summary>
    ///     Represents the singleton scope lifecycle.
    /// </summary>
    public class SingletonScopeLifecycle : ScopeLifecycleBase
    {
        #region Fields

        private volatile object _singleton;

        #endregion

        #region Overrides of ScopeLifecycleBase

        /// <summary>
        ///     Resolves instance for the specified <see cref="IBindingContext" /> from scope.
        /// </summary>
        /// <returns>An instance of the service.</returns>
        protected override object GetObjectFromScope()
        {
            if (_singleton == null)
            {
                lock (Locker)
                {
                    if (_singleton == null)
                        _singleton = ResolveCurrentService();
                }
            }
            return _singleton;
        }

        /// <summary>
        ///     Gets all created objects in the current scope.
        /// </summary>
        protected override IList<object> GetObjectsFromScope()
        {
            if (_singleton == null)
                return InjectorUtilsInternal.EmptyParams;
            return new[] {_singleton};
        }

        /// <summary>
        ///     Clears the current scope.
        /// </summary>
        protected override void ClearScope()
        {
            _singleton = null;
        }

        #endregion
    }
}